<?php

namespace app\common\model;

use think\cache\driver\Redis;
use think\Db;
use think\Model;

class GoodsSpike extends Model
{
    // 表名
    protected $name = 'goods_spike';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'start_time_text',
	    'end_time_text',
        'create_time_text',
        'update_time_text',
	    'status_text'
    ];

//状态0下架1待开始2抢购中3已抢完
	const STATUS_N = 0;
	const STATUS_W = 1;
	const STATUS_ING = 2;
	const STATUS_F = 3;
 
	public static $statusList = [
		self::STATUS_W => '待开始',
		self::STATUS_N => '已取消',
		self::STATUS_ING => '抢购中',
		self::STATUS_F => '已抢完',
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}



    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['start_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	public function getEndTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['end_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStartTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	protected function setEndTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

	public function goods(){
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function getGoods($goodsId, $number, $priceId, $userId){
		if(!$goodsId || !$number || $number < 1){
			$this->error = '请选择结算商品和购买数量';
			return false;
		}
		
		$redis = new \Redis();
		if(!$redis->connect('127.0.0.1', 6379)){
			$this->error = 'redis连接出错';
			return false;
		};
		
		$redis->auth(config('redis.password'));
		
		//秒杀商品信息
		$spikeGoodsInfoKey = 'spike_goods_'.$goodsId;
		$user_queue_key = "spike_goods_".$goodsId."_user";//当前商品队列的用户情况
		$goods_number_key = "spike_goods_number_".$goodsId;//当前商品的库存队列
		
		
		$spikeGoodsInfo = $redis->get($spikeGoodsInfoKey);
		if(!$spikeGoodsInfo) {
			$spikeGoodsInfo = Db::name('goodsSpike')
				->where(['goods_id' => $goodsId])
				->find();
			if(!$spikeGoodsInfo) {
				$this->error = '秒杀商品不存在或已下架';
				return false;
			}
			
			$spikeGoodsInfo = json_encode($spikeGoodsInfo);
			$redis->set($spikeGoodsInfoKey, $spikeGoodsInfo);
		}
		
		$spikeGoodsInfo = json_decode($spikeGoodsInfo, true);
		if($spikeGoodsInfo['start_time'] >= time()) {
			$this->error = '该秒杀未开始';
			return false;
		}
		
		if($spikeGoodsInfo['end_time'] <= time()) {
			$this->error = '该秒杀已结束';
			return false;
		}
		
		if($redis->hGet($user_queue_key, $userId)) {
			$this->error = '你已经抢购过了';
			return false;
		}
		
		$getUserRedis = $redis->hGetAll($user_queue_key);
		$gnRedis = $redis->llen($goods_number_key);
		/* 如果没有会员进来队列库存 */
		if(!count($getUserRedis) && !$gnRedis){
			for ($i = 0; $i < $spikeGoodsInfo['store_number']; $i ++) {
				$r = $redis->lpush($goods_number_key, 1);
			}
			
			$gnRedis = $redis->llen($goods_number_key);
		}
		if(!$gnRedis){
			$this->error = "该商品已经抢完了！".$goods_number_key;
			return false;
		}
		//商品抢购用户
		//商品库存
		
		if(isset($priceId) && !empty($priceId)){
			$row = Db::name('goods_spec_price')->alias('p')
				->join('goods g', 'p.goods_id = g.id','left')
				->join('business b', 'g.business_id = b.id', 'left')
				->where(['p.id' => $priceId, 'g.id' => $goodsId])
				->field('p.id as price_id, p.goods_id, p.sku,
					g.goods_name, g.shop_price, g.original_image, g.chain_no,
					g.store_count as goods_store, g.business_id,g.commission,
					g.goods_no, g.market_price, g.cost_price, g.give_integral,
					g.is_free_shipping, g.shipping_template_id, g.weight, g.use_point as point, g.give_balance as sendmoney,
					g.goods_type, g.use_day, g.send_number, g.send_day, g.input_ids, g.open_user_grade,
					p.price as spec_price, p.store_count as spec_store, p.sku,
					p.spec_name, b.name as business_name')
				->find();
			if(!$row){
				$this->error = '商品不存在';
				return false;
			}
			
			$row['spec_price'] = $spikeGoodsInfo['price'];
			$row['number'] = $number;
			$goods[] = $row;
		} else {
			$priceItem = Db::name('goods_spec_price')->where(['goods_id' => $goodsId])->find();
			if($priceItem && (!isset($priceId) || empty($priceId))){
				$this->error = '请选择商品规格';
				return false;
			}
			
			$row = Db::name('goods')->alias('g')
				->where(['g.id' => $goodsId])
				->join('business b', 'g.business_id = b.id', 'left')
				->field('g.id as goods_id, g.goods_name, g.shop_price,
					g.original_image, g.store_count as goods_store,
					g.business_id, g.goods_no, g.market_price,g.commission,
					g.is_free_shipping, g.shipping_template_id, g.use_point as point, g.give_balance as sendmoney,
					g.cost_price, g.give_integral,g.weight,
					g.goods_type, g.use_day, g.send_number, g.send_day, g.input_ids, g.open_user_grade,
					b.name as business_name')
				->find();
			if(!$row){
				$this->error = '商品不存在';
				return false;
			}
			
			$row['spec_price'] = $row['spec_store'] = $row['spec_name'] = $row['price_id'] = '';
			$row['shop_price'] = $spikeGoodsInfo['price'];
			
			$row['number'] = $number;
			$goods[] = $row;
		}
		return $goods;
	}
}
